package com.hibiscusking.pet.service.impl;

import com.hibiscusking.pet.domain.PetType;
import com.hibiscusking.pet.mapper.PetTypeMapper;
import com.hibiscusking.pet.service.IPetTypeService;
import com.hibiscusking.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hibiscusking
 * @since 2022-10-28
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;
    @Override
    public List<PetType> getPetTypeTree() {
        List<PetType> types = new ArrayList<>();
        List<PetType> petTypesAll = petTypeMapper.findAll();
        // stream
        Map<Long, PetType> parentMap = petTypesAll.stream().collect(Collectors.toMap(PetType::getId, e -> e));
        // 遍历
        for (PetType type : petTypesAll) {
            if (null == type.getPid()) {
                // 它就是最大的那个die
                types.add(type);
            } else {
                PetType petType = parentMap.get(type.getPid());
                if (null != petType){
                    petType.getChildren().add(type);
                }
            }
        }
        return types;

    }
}
